package com.spring_mysql_redis.service.impl;

import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.AbstractWrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spring_mysql_redis.entity.*;
import com.spring_mysql_redis.mapper.CommentMapper;
import com.spring_mysql_redis.mapper.DynamicMapper;
import com.spring_mysql_redis.mapper.UserLikesMapper;
import com.spring_mysql_redis.model.ResultFormat;
import com.spring_mysql_redis.service.CommentService;
import com.spring_mysql_redis.service.DynamicService;
import com.spring_mysql_redis.service.UserLikesService;
import com.spring_mysql_redis.utils.RedisUtil;
import com.spring_mysql_redis.utils.ResultUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 */
@Service
@Transactional
public class DynamicServiceImpl extends ServiceImpl<DynamicMapper, Dynamic> implements DynamicService {

    private Logger logger = LoggerFactory.getLogger(DynamicService.class);

    @Autowired
    private DynamicMapper dynamicMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Resource
    private UserLikesMapper userLikesMapper;

    @Autowired
    private CommentService commentService;
    @Autowired
    private UserLikesService userLikesService;



    /**
     * 分页查询用户信息
     *
     * @param dynamic
     * @param page
     * @param limit
     * @return
     */
    @Override
    public IPage<Dynamic> selectDynamicList(Dynamic dynamic, Integer page, Integer limit) {
        AbstractWrapper wrapper = new QueryWrapper<Dynamic>();
        if (dynamic != null) {
            if (!StringUtils.isEmpty(dynamic.getContent())) {
                wrapper.like("content", dynamic.getContent());
            }

        }
        //查询状态为0 的数据
        /*wrapper.eq("state", 0);*/
        /**
         * 对查询数据进行排序(根据注册时间进行排序)
         * orderByAsc:升序
         * orderByDesc:降序
         */
        wrapper.orderByAsc("create_time");
        Page<Dynamic> iPage = new Page<Dynamic>(page, limit);
        Page<Dynamic> pgLinksPage = dynamicMapper.selectPage(iPage, wrapper);
        return pgLinksPage;
    }

    /**
     * 分页查询用户信息
     *
     * @param userDynamic
     * @return
     */
    @Override
    public Page<UserDynamic> selectUserDynamicList(Page<UserDynamic> userDynamic) {
        return dynamicMapper.getUserDynamicList(userDynamic);
    }

    @Override
    public Page<UserDynamic> selectOneUserDynamicList(Page<UserDynamic> userDynamic, Integer userId) {
        return dynamicMapper.getOneUserDynamicList(userDynamic, userId);
    }

    @Override
    public Dynamic selectDynamicOne(Integer id, Users user) {

        //显示动态内容
        Dynamic oneDynamic = dynamicMapper.selectOne(new QueryWrapper<Dynamic>().eq("id", id));
        if(user != null){
            logger.info("-----------------session进入 查询动态点赞-----------------");
            //用户已登录，查询用户是否在该动态点赞
            UserLikes userLikes = userLikesMapper.selectOne(new QueryWrapper<UserLikes>().eq("dynamic_id", id).eq("user_id", user.getId()));
            //已点赞界面操作
            logger.info(userLikes+"-----------------session进入 查询动态点赞-----------------");
            if (userLikes.getState() == 1) {
                System.out.println(userLikes);
            }
            //未点赞界面操作
            if (userLikes.getState() == 0) {
                System.out.println(userLikes);
            }
        }
        return oneDynamic;
    }

    /**
     * 添加
     *
     * @param dynamic
     * @return
     */
    @Override
    public ResultFormat saveDynamic(Dynamic dynamic) {
//        imgUrl = imgUrl.replace("[","").replace("]","");
        logger.info("-----------------进入service实现层 添加动态-----------------");
        if (dynamic.getContent() == null || dynamic.getContent().equals("")) {
            return ResultUtil.error(101, "未填写内容");
        }
        Integer insert = dynamicMapper.insert(dynamic);
        if (insert > 0) {
            redisUtil.lSet("dynamic_id", dynamic.getId());
            redisUtil.set("sp_dynamic:" + dynamic.getId(), dynamic);
        }
        return ResultUtil.success();
    }

    /**
     * 修改
     *
     * @param dynamic
     * @return
     */
    @Override
    public Integer updateDynamic(Dynamic dynamic) {
        logger.info("-----------------进入service实现层 修改用户信息-----------------");
        /**
         * 查询标签名称是否存在
         * 如果存在那就返回提示已经存在
         * 如果不存在那就修改
         */
        if (dynamic != null) {
            if (dynamic.getId() != null) {
                Dynamic pgLabelsByIdInfo = dynamicMapper.selectById(dynamic.getId());
                /**
                 *
                 * 可修改其它数据
                 */
                if (pgLabelsByIdInfo != null) {
                    logger.info("pgLabelsByIdInfo={}", pgLabelsByIdInfo);
                    Integer updateById = dynamicMapper.updateById(dynamic);
                    if (updateById > 0) {
                        redisUtil.set("sp_dynamic:" + dynamic.getId(), dynamic);
                        return 200;
                    }
                }

            }
        }
        return 100;
    }


    /**
     * 删除
     *
     * @param id
     * @return
     */
    @Override
    public Integer deleteDynamicId(Integer id,Integer userId) {
        logger.info("-----------------进入service实现层 删除用户信息-----------------");
        Dynamic one = dynamicMapper.selectOne(new LambdaQueryWrapper<Dynamic>().eq(Dynamic::getId, id).eq(Dynamic::getUserId, userId));
        if (one != null){
            Integer deleteById = dynamicMapper.deleteById(id);
            if (deleteById > 0) {
                Long delete = redisUtil.delete("sp_dynamic:" + String.valueOf(id));
                //从评论表删除该动态评论
                commentService.delCommentList(id);
                //从点赞表删除该动态点赞
                userLikesService.delLikeList(id);
                logger.info("-----------------"+delete+"-----------------");
                return 200;
            }
            return 100;
        }
        return 100;
    }

}
